package org.agile4j.rpc.client.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.agile4j.rpc.client.utils.SerializtionUtil;

import java.util.List;

/**
 * RPC 解码器
 * 
 * 扩展 Netty 的ByteToMessageDecoder抽象类的decode方法
 * Created by Administrator on 2016/8/12.
 */
public class RpcDecoder extends ByteToMessageDecoder {
    private Class<?> genericClass ;

    public RpcDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 如果没有接收完Header部分（4字节），直接退出该方法
        if (in.readableBytes() < 4) {
        	return ;
        }
    	in.markReaderIndex() ;
    	int dataLength = in.readInt() ;
        if (in.readableBytes() < dataLength) {
			in.resetReaderIndex() ;
			return ;
		}
        byte[] data = new byte[dataLength] ;
        in.readBytes(data) ;
        out.add(SerializtionUtil.deserialize(data, genericClass));
    }
}
